@file:Suppress("UNREACHABLE_CODE")

package com.zkjd.lingdong.ui.function

import android.content.Context
import android.graphics.Bitmap
import android.graphics.drawable.Drawable
import android.widget.Toast
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyGridState
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.items
import androidx.compose.foundation.lazy.grid.rememberLazyGridState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material.icons.filled.Clear
import androidx.compose.material.icons.filled.RotateLeft
import androidx.compose.material.icons.filled.RotateRight
import androidx.compose.material.icons.filled.Save
import androidx.compose.material.icons.filled.TouchApp
import androidx.compose.material.icons.outlined.Apps
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Surface
import androidx.compose.material3.Switch
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.asImageBitmap
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.platform.LocalLifecycleOwner
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.Density
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.window.Dialog
import androidx.core.graphics.drawable.toBitmap
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.repeatOnLifecycle
import androidx.navigation.NavController
import com.zkjd.lingdong.data.FunctionsConfig
import com.zkjd.lingdong.model.ButtonFunction
import com.zkjd.lingdong.model.ButtonType
import com.zkjd.lingdong.model.FunctionCategory
import com.zkjd.lingdong.ui.home.ConfirmDeleteDialog
import com.zkjd.lingdong.ui.theme.CardBackground
import com.zkjd.lingdong.ui.theme.Error

/**
 * 新的功能配置屏幕
 */
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun FunctionScreen(
    navController: NavController,
    viewModel: FunctionViewModel = hiltViewModel(),
    deviceMac: String
) {
    // 从ViewModel获取当前选中的按钮类型
    val selectedButtonType by viewModel.selectedButtonType.collectAsState()
    
    // 当前选择的功能
    var selectedFunction by remember { mutableStateOf<ButtonFunction?>(null) }

    // 获取功能配置实例
    val functionsConfig = remember { FunctionsConfig.getInstance(viewModel.getContext()) }
    
    // 获取临时存储的按钮功能
    val tempButtonFunctions by viewModel.tempButtonFunctions.collectAsState()
    // 判断是否旋钮
    val isRoty by viewModel.isRoty.collectAsState()

    // 判断是否保存
    val isSave by viewModel.isSave.collectAsState()

    val useCarTypeName by viewModel.useCarTypeName.collectAsState()

    var showSaveDialog by remember { mutableStateOf(false) }
    // 获取设备防误触状态值
    val preventAccidental by viewModel.isPreventAccidental.collectAsState()

    var showTestDialog by remember { mutableStateOf(false) }


    val context = LocalContext.current
    var toast: Toast? = null
    val lifecycle = LocalLifecycleOwner.current.lifecycle
    LaunchedEffect(key1 = true) {
        lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED) {
            viewModel.uiEvents.collect { event ->
                when (event) {
                    is FunctionViewModel.UiEvent.ShowToast -> {
                        if(toast==null) {
                            toast = Toast.makeText(context, event.message, Toast.LENGTH_SHORT)
                        }else{
                            //有新的消息即时更新，不用等待上一个消息显示完成以后再显示，造成延时很长的感觉
                            toast?.setText(event.message)
                        }
                        toast?.show()
                    }

                    is FunctionViewModel.UiEvent.Navigate -> TODO()
                }
            }
        }
    }

    // 监听从应用选择页面返回的结果
    LaunchedEffect(navController) {
        navController.currentBackStackEntryFlow.collect { entry ->
            val id = entry.savedStateHandle.get<String>("selected_app_id")
            val name = entry.savedStateHandle.get<String>("selected_app_name")
            val actionCode = entry.savedStateHandle.get<String>("selected_app_action_code")
            
            if (id != null && name != null && actionCode != null) {
                // 重新构建ButtonFunction对象，确保包含所有必要信息
                val function = ButtonFunction(
                    id = id,
                    category = FunctionCategory.APP,  // 明确设置类别为APP
                    name = name,
                    actionCode = actionCode,
                    iconResId = 0,  // APP类型使用通用图标，不需要特定的资源ID
                    configWords = ""
                )
                selectedFunction = function
                // 临时保存功能，同时保存完整的功能信息
                viewModel.tempSaveButtonFunction(selectedButtonType, function)
                
                // 清除SavedStateHandle中的数据
                entry.savedStateHandle.remove<String>("selected_app_id")
                entry.savedStateHandle.remove<String>("selected_app_name")
                entry.savedStateHandle.remove<String>("selected_app_action_code")
            }
        }
    }
    
    // 新增：监听按钮类型变化，更新选中的功能
    LaunchedEffect(selectedButtonType, tempButtonFunctions) {
        // 优先从临时存储中获取功能
        selectedFunction = tempButtonFunctions[selectedButtonType]
    }

    // 根据按钮类型获取适合的功能列表
    val functionsList = remember(selectedButtonType) {
        when {
            selectedButtonType in ButtonType.ROTATE_TYPES -> functionsConfig.getRotaryFunctions(useCarTypeName)
            else -> functionsConfig.getNonRotaryFunctions(useCarTypeName)
        }
    }

    // 加载设备当前的功能配置
    LaunchedEffect(deviceMac) {
        viewModel.loadDeviceFunctions(deviceMac)
    }

    Scaffold(
        topBar = {
            TopAppBar(
                title = { Text("按键功能配置") },
                colors = TopAppBarDefaults.topAppBarColors(
                    containerColor = Color(0xFF1C1C28),//MaterialTheme.colorScheme.primary,
                    titleContentColor = Color(0xFFFFFFFF),//MaterialTheme.colorScheme.onPrimary
                ),
                navigationIcon = {
                    IconButton(onClick = {
                        if(isSave){
                            showSaveDialog=true
                        }else{navController.popBackStack()}
                    }) {
                        Icon(
                            imageVector = Icons.Default.ArrowBack,
                            contentDescription = "返回",
                            tint =MaterialTheme.colorScheme.onPrimary,
                            modifier=Modifier.size(55.dp)
                        )
                    }
                },
                actions = {
                    // 添加保存所有按钮
                    IconButton(onClick = {
                        // 保存所有按键功能
                        viewModel.saveAllButtonFunctions(deviceMac)
                        navController.popBackStack()
                    }) {
                        Icon(
                            imageVector = Icons.Default.Save,
                            contentDescription = "保存所有",
                            tint = MaterialTheme.colorScheme.onPrimary,
                            modifier=Modifier.size(55.dp)
                        )
                    }
                }
            )
        }
    ) { paddingValues ->
        Column(
            modifier = Modifier
                .fillMaxSize()
                .padding(paddingValues)
        ) {
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(bottom = 24.dp),
                horizontalArrangement = Arrangement.Start,
                verticalAlignment = Alignment.Bottom
            ) {
                // 按钮类型选择
                ButtonTypeSelector(
                    isRoty = isRoty,
                    selectedButtonType = selectedButtonType,
                    onButtonTypeSelected = { buttonType ->
                        // 更新 ViewModel 中的状态
                        viewModel.setSelectedButtonType(buttonType)
                    }
                )

                // 显示当前功能配置的图标和名称（无论是否有功能，都显示）
                SelectedFunctionCard(
                    function = selectedFunction,
                    buttonType = selectedButtonType,
                    onClearFunction = {
                        // 清除当前选择的功能
                        selectedFunction = null
                        // 将null值保存到临时存储，表示清除此功能
                        viewModel.tempSaveButtonFunction(selectedButtonType, null)
                    }
                )
                if(isRoty) {
                    Row(
                        modifier = Modifier
                            .fillMaxWidth(),
                        horizontalArrangement = Arrangement.End,
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        Text(
                            text = "防误触",
                            style = MaterialTheme.typography.titleMedium,
                            modifier = Modifier.padding(16.dp)
                        )
                        Spacer(modifier = Modifier.width(10.dp))
                        Switch(
                            checked = preventAccidental,
                            onCheckedChange = { viewModel.setPreventAccidental(deviceMac) }
                        )
                        Spacer(modifier = Modifier.width(20.dp))

                    }
                }
            }
            Text(
                text = "选择功能",
                style = MaterialTheme.typography.titleMedium,
                modifier = Modifier.padding(16.dp)
            )
            
            FunctionGrid(
                functions = functionsList,
                selectedFunction = selectedFunction,
                onFunctionSelected = { function ->
                    selectedFunction = function
                    // 临时保存功能
                    viewModel.tempSaveButtonFunction(selectedButtonType, function)
                },
                onAppSelectionRequested = {
                    // 导航到应用选择页面
                    navController.navigate("app_selection")
                },
                isAppSelected = selectedFunction?.category == FunctionCategory.APP,
                isRotaryType = selectedButtonType in ButtonType.ROTATE_TYPES
            )
        }

        // 删除确认对话框
        if (showSaveDialog) {
            ConfirmSaveDialog(
                onDismiss = {
                    showSaveDialog = false
                    navController.popBackStack()},
                onConfirm = {
                    viewModel.saveAllButtonFunctions(deviceMac)
                    showSaveDialog = false
                    navController.popBackStack()
                }
            )
        }
    }
}


/**
 * 按钮类型选择器
 */
@Composable
fun ButtonTypeSelector(
    isRoty: Boolean,
    selectedButtonType: ButtonType,
    onButtonTypeSelected: (ButtonType) -> Unit
) {
    Column(modifier = Modifier.padding(16.dp)) {
        Text(
            text = "选择按键类型",
            style = MaterialTheme.typography.titleMedium
        )
        
        Spacer(modifier = Modifier.height(8.dp))
        
        Row(

            horizontalArrangement = Arrangement.spacedBy(8.dp)
        ) {
            ButtonTypeCard(
                type = ButtonType.SHORT_PRESS,
                name = "短按",
                icon = Icons.Default.TouchApp,
                isSelected = selectedButtonType == ButtonType.SHORT_PRESS,
                onClick = { onButtonTypeSelected(ButtonType.SHORT_PRESS) }
            )
            
//            ButtonTypeCard(
//                type = ButtonType.LONG_PRESS,
//                name = "长按",
//                icon = Icons.Default.TouchApp,
//                isSelected = selectedButtonType == ButtonType.LONG_PRESS,
//                onClick = { onButtonTypeSelected(ButtonType.LONG_PRESS) }
//            )
            
            ButtonTypeCard(
                type = ButtonType.DOUBLE_CLICK,
                name = "双击",
                icon = Icons.Default.TouchApp,
                isSelected = selectedButtonType == ButtonType.DOUBLE_CLICK,
                onClick = { onButtonTypeSelected(ButtonType.DOUBLE_CLICK) }
            )
            if(isRoty) {
                ButtonTypeCard(
                    type = ButtonType.LEFT_ROTATE,
                    name = "旋转",
                    icon = Icons.Default.RotateLeft,
                    isSelected = selectedButtonType == ButtonType.LEFT_ROTATE,
                    onClick = { onButtonTypeSelected(ButtonType.LEFT_ROTATE) }
                )
            }
        }
    }
}

/**
 * 按钮类型卡片
 */
@Composable
fun ButtonTypeCard(
    type: ButtonType,
    name: String,
    icon: ImageVector,
    isSelected: Boolean,
    onClick: () -> Unit
) {
    Card(
        modifier = Modifier
            .clickable(onClick = onClick),
        colors = CardDefaults.cardColors(
            containerColor = if (isSelected) 
                MaterialTheme.colorScheme.primaryContainer 
            else 
                MaterialTheme.colorScheme.surface
        ),
        shape = RoundedCornerShape(8.dp),
        elevation = CardDefaults.cardElevation(
            defaultElevation = if (isSelected) 4.dp else 2.dp
        )
    ) {
        Column(
            modifier = Modifier
                .width(120.dp)
                .padding(12.dp),
            horizontalAlignment = Alignment.CenterHorizontally
        ) {
            Box(
                modifier = Modifier
                    .size(100.dp)
                    .clip(CircleShape)
                    .background(
                        if (isSelected)
                            MaterialTheme.colorScheme.primary.copy(alpha = 0.2f)
                        else
                            MaterialTheme.colorScheme.surfaceVariant
                    ),
                contentAlignment = Alignment.Center
            ) {
                Icon(
                    imageVector = icon,
                    contentDescription = null,
                    tint = if (isSelected)
                        MaterialTheme.colorScheme.primary
                    else
                        MaterialTheme.colorScheme.onSurfaceVariant,
                    modifier = Modifier.size(70.dp)
                )
            }
            
            Spacer(modifier = Modifier.height(8.dp))
            
            Text(
                text = name,
                style = MaterialTheme.typography.bodyMedium,
                color = if (isSelected)
                    MaterialTheme.colorScheme.onPrimaryContainer
                else
                    MaterialTheme.colorScheme.onSurface,
                fontWeight = if (isSelected) FontWeight.Bold else FontWeight.Normal
            )
        }
    }
}

/**
 * 显示当前选择的功能卡片
 */
@Composable
fun SelectedFunctionCard(
    function: ButtonFunction?,
    buttonType: ButtonType,
    onClearFunction: () -> Unit = {}
) {
    Card(
        modifier = Modifier
            .width(350.dp)
            .height(180.dp)
            .padding(16.dp),
        colors = CardDefaults.cardColors(
            containerColor = MaterialTheme.colorScheme.secondaryContainer
        ),
        elevation = CardDefaults.cardElevation(defaultElevation = 2.dp)
    ) {
        Row(
            modifier = Modifier
                .padding(30.dp),
            verticalAlignment = Alignment.CenterVertically,
        ) {
            // 使用通用图标组件
            FunctionIcon(
                iconResId = function?.iconResId,
                name = function?.name ?: buttonType.name,
                category = function?.category,
                actionCode = function?.actionCode,
                size = 64.dp,
                iconSize = 78.dp,
                backgroundColor = MaterialTheme.colorScheme.secondary.copy(alpha = 0.2f),
                contentColor = MaterialTheme.colorScheme.secondary,
                defaultIcon = when {
                    function == null -> when(buttonType) {
                        ButtonType.SHORT_PRESS -> Icons.Default.TouchApp
                        ButtonType.LONG_PRESS -> Icons.Default.TouchApp
                        ButtonType.DOUBLE_CLICK -> Icons.Default.TouchApp
                        ButtonType.LEFT_ROTATE -> Icons.Default.RotateLeft
                        ButtonType.RIGHT_ROTATE -> Icons.Default.RotateRight
                        else -> null
                    }
                    else -> null
                }
            )
            
            Spacer(modifier = Modifier.width(16.dp))
            
            Column(
                modifier = Modifier.weight(1f)
            ) {
                Text(
                    text = when(buttonType) {
                        ButtonType.SHORT_PRESS -> "短按功能"
                        ButtonType.LONG_PRESS -> "长按功能"
                        ButtonType.DOUBLE_CLICK -> "双击功能"
                        ButtonType.LEFT_ROTATE -> "旋转功能 (左旋)"
                        ButtonType.RIGHT_ROTATE -> "旋转功能 (右旋)"
                        else -> ""
                    },
                    style = MaterialTheme.typography.titleSmall,
                    color = MaterialTheme.colorScheme.onSurfaceVariant
                )
                
                Text(
                    text = when {
                        function?.category == FunctionCategory.APP -> "开启应用: ${function.name}"
                        function != null -> function.name
                        else -> "未设置功能"
                    },
                    style = MaterialTheme.typography.titleMedium,
                    color = MaterialTheme.colorScheme.onSecondaryContainer,
                    fontWeight = FontWeight.Bold
                )
            }

            // 添加清除按钮
            if (function != null) {
                IconButton(
                    onClick = onClearFunction,
                    modifier = Modifier.size(78.dp)
                ) {
                    Icon(
                        imageVector = Icons.Default.Clear,
                        contentDescription = "清除功能",
                        tint = MaterialTheme.colorScheme.onSecondaryContainer.copy(alpha = 0.6f)
                    )
                }
            }
        }
    }
}

/**
 * 功能网格
 */
@Composable
fun FunctionGrid(
    functions: List<ButtonFunction>,
    selectedFunction: ButtonFunction?,
    onFunctionSelected: (ButtonFunction) -> Unit,
    onAppSelectionRequested: () -> Unit,
    isAppSelected: Boolean,
    isRotaryType: Boolean,
    state: LazyGridState = rememberLazyGridState()
) {
    LazyVerticalGrid(
        state = state,
        columns = GridCells.Fixed(4),
        contentPadding = PaddingValues(horizontal = 16.dp, vertical = 8.dp),
        horizontalArrangement = Arrangement.spacedBy(25.dp),
        verticalArrangement = Arrangement.spacedBy(25.dp)
    ) {
        items(functions) { function ->
            FunctionCard(
                name = function.name,
                iconResId = function.iconResId,
                isAppSelector = function.id == "launch_app",
                // 修改选中状态判断逻辑
                isSelected = if (function.id == "launch_app") {
                    selectedFunction?.category == FunctionCategory.APP
                } else {
                    selectedFunction?.id == function.id
                },
                onClick = {
                    // 如果是开启应用功能，直接进入应用选择页面
                    if (function.id == "launch_app") {
                        onAppSelectionRequested()
                    } else {
                        onFunctionSelected(function)
                    }
                }
            )
        }
    }
}

/**
 * 通用功能图标组件
 */
@Composable
fun FunctionIcon(
    iconResId: Int?,
    name: String,
    category: FunctionCategory? = null,
    actionCode: String? = null,
    size: Dp = 64.dp,
    iconSize: Dp = 64.dp,
    backgroundColor: Color = MaterialTheme.colorScheme.surfaceVariant,
    contentColor: Color = MaterialTheme.colorScheme.onSurfaceVariant,
    defaultIcon: ImageVector? = null
) {
    val context = LocalContext.current
    val packageManager = context.packageManager
    var appIcon by remember { mutableStateOf<Bitmap?>(null) }
    if (category==FunctionCategory.APP) {
        //加载应用图标
        val packageName = actionCode?.substring(4)
        packageName?.let {
            val icon: Drawable? = packageManager.getApplicationIcon(it)
            icon?.let {
                appIcon = it.toBitmap(200, 200)
            }
        }
    }

    Box(
        contentAlignment = Alignment.Center
    ) {
        when {
            // 如果是APP类别，显示应用图标
            category == FunctionCategory.APP -> {
                if (appIcon != null) {
                    // 显示实际应用图标
                    Image(
                        bitmap = appIcon!!.asImageBitmap(),
                        contentDescription = null,
                        modifier = Modifier.size(iconSize),
                        contentScale = ContentScale.Fit
                    )
                }
                else {
                    // 使用默认图标
                    Icon(
                        imageVector = Icons.Outlined.Apps,
                        contentDescription = null,
                        modifier = Modifier.size(iconSize)
                    )
                }
            }
            // 如果有资源ID且不为0，尝试显示资源图标
            iconResId != null && iconResId != 0 -> {
                val isValidResource = remember(iconResId) {
                    isSupportedImageResource(context, iconResId)
                }
                
                if (isValidResource) {
                    Icon(
                        painter = painterResource(id = iconResId),
                        contentDescription = null,
                        tint = contentColor,
                        modifier = Modifier.size(iconSize),
                    )
                } else {
                    // 如果资源无效，回退到默认图标或文本
                    FallbackIcon(
                        defaultIcon = defaultIcon,
                        name = name,
                        contentColor = contentColor,
                        iconSize = iconSize
                    )
                }
            }
            // 如果没有资源ID，显示默认图标或文本
            else -> {
                FallbackIcon(
                    defaultIcon = defaultIcon,
                    name = name,
                    contentColor = contentColor,
                    iconSize = iconSize
                )
            }
        }
    }
}

@Composable
fun FallbackIcon(
    defaultIcon: ImageVector?,
    name: String,
    contentColor: Color,
    iconSize: Dp
) {
    if (defaultIcon != null) {
        Icon(
            imageVector = defaultIcon,
            contentDescription = null,
            tint = contentColor,
            modifier = Modifier.size(iconSize)
        )
    } else {
        Text(
            text = name.firstOrNull()?.toString() ?: "?",
            style = MaterialTheme.typography.bodyLarge,
            color = contentColor
        )
    }
}

private fun isSupportedImageResource(context: Context, resourceId: Int): Boolean {
    return try {
        val resourceTypeName = context.resources.getResourceTypeName(resourceId)
        when (resourceTypeName) {
            "drawable", "mipmap" -> true  // 所有drawable和mipmap资源都是支持的图片资源
            else -> false
        }
    } catch (e: Exception) {
        false
    }
}

/**
 * 功能卡片
 */
@Composable
fun FunctionCard(
    name: String,
    iconResId: Int?,
    isAppSelector: Boolean,
    isSelected: Boolean,
    onClick: () -> Unit
) {
    Box(
        modifier = Modifier.fillMaxWidth()
    ) {
        Card(
            modifier = Modifier
                .fillMaxWidth()
                .height(200.dp)
                .clickable(onClick = onClick),
            colors = CardDefaults.cardColors(
                containerColor = if (isSelected)
                    MaterialTheme.colorScheme.primaryContainer
                else
                    MaterialTheme.colorScheme.surface
            ),
            shape = RoundedCornerShape(8.dp),
            elevation = CardDefaults.cardElevation(
                defaultElevation = if (isSelected) 4.dp else 2.dp
            )
        ) {
            Column(
                modifier = Modifier
                    .fillMaxSize()
                    .padding(8.dp),
                horizontalAlignment = Alignment.CenterHorizontally,
                verticalArrangement = Arrangement.Center
            ) {
                // 使用通用图标组件
                FunctionIcon(
                    iconResId = iconResId,
                    name = name,
                    category = if (isAppSelector) FunctionCategory.APP else null,
                    size = 64.dp,
                    iconSize = 78.dp,
                    backgroundColor = if (isSelected)
                        MaterialTheme.colorScheme.primary.copy(alpha = 0.2f)
                    else
                        MaterialTheme.colorScheme.surfaceVariant,
                    contentColor = if (isSelected)
                        MaterialTheme.colorScheme.primary
                    else
                        MaterialTheme.colorScheme.onSurfaceVariant
                )

                Spacer(modifier = Modifier.height(8.dp))

                Text(
                    text = name,
                    style = MaterialTheme.typography.bodyMedium,
                    color = if (isSelected)
                        MaterialTheme.colorScheme.onPrimaryContainer
                    else
                        MaterialTheme.colorScheme.onSurface,
                    fontWeight = if (isSelected) FontWeight.Bold else FontWeight.Normal,
                    maxLines = 2,
                    overflow = TextOverflow.Ellipsis,
                    textAlign = TextAlign.Center
                )
            }
        }

        // 选中状态标志
        if (isSelected) {
            Box(
                modifier = Modifier
                    .padding(top = 8.dp, end = 8.dp)  // 使用 padding 代替 offset
                    .size(16.dp)
                    .clip(CircleShape)
                    .background(MaterialTheme.colorScheme.primary)
                    .align(Alignment.TopEnd)
            )
        }
    }
}
@Composable
fun ConfirmSaveDialog(
    onDismiss: () -> Unit,
    onConfirm: () -> Unit
) {

    Dialog(onDismissRequest = onDismiss) {
        val widthPixels = LocalContext.current.resources.displayMetrics.widthPixels
        val targetDensity = widthPixels / 1060f
        CompositionLocalProvider(LocalDensity provides Density(density = targetDensity)) {
            Surface(
                shape = RoundedCornerShape(16.dp),
                color = CardBackground
            ) {
                Column(
                    modifier = Modifier
                        .padding(24.dp)
                        .width(300.dp),
                    horizontalAlignment = Alignment.CenterHorizontally
                ) {
                    Text(
                        text = "温馨提醒",
                        color = Color.White,
                        fontSize = 18.sp,
                        fontWeight = FontWeight.Bold
                    )

                    Spacer(modifier = Modifier.height(16.dp))

                    Text(
                        text = "您更换了功能项，需要保存吗？",
                        color = Color.White
                    )

                    Spacer(modifier = Modifier.height(24.dp))

                    Row(
                        modifier = Modifier.fillMaxWidth(),
                        horizontalArrangement = Arrangement.End
                    ) {
                        TextButton(onClick = onDismiss) {
                            Text("不需要", color = Color.White)
                        }

                        TextButton(onClick = onConfirm) {
                            Text("保存", color = Color.White)
                        }
                    }
                }
            }
        }
    }
}


